import { reactive, ref, onMounted, computed } from "vue";
import type { FormInstance, FormRules, UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import { imageUpload } from "@/api/common";
import { useUserStore } from "@/store/modules/user";
import { useRoute } from "vue-router";
import {
  addArticle,
  getArticleDetail,
  updateArticle
} from "@/api/community/index";
import { QNURL } from "@/config/urlConfig";

export function usePublish() {
  const userStore = useUserStore();
  // const router = useRouter();
  const route = useRoute();

  const articleId = route.query.id;
  const type = Number(route.query.type);

  const userInfo = computed(() => userStore.userInfo);

  interface RuleForm {
    id: string;
    title: any;
    content: any;
    cover: string;
    digest: string;
  }

  const formSize = ref("default");
  const ruleFormRef = ref<FormInstance>();
  const ruleForm = reactive<RuleForm>({
    id: "",
    title: "",
    content: "",
    cover: "",
    digest: ""
  });

  const rules = reactive<FormRules<RuleForm>>({
    digest: [{ required: true, message: "请填写摘要", trigger: "blur" }],
    content: [{ required: true, message: "请填写内容", trigger: "blur" }],
    title: [{ required: true, message: "请输入标题", trigger: "blur" }],
    cover: [{ required: true, message: "请上传封面", trigger: "blur" }]
  });

  const beforeAvatarUpload: UploadProps["beforeUpload"] = file => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isJpgOrPng) {
      ElMessage.error("只能上传 JPG/PNG 图片格式的文件");
      return false;
    }
    if (!isLt2M) {
      ElMessage.error("文件大小超过 10MB 的限制");
      return false;
    }

    // 使用自定义的方式上传文件
    const formData = new FormData();
    formData.append("image", file);

    uploadFile(formData);

    return false;
  };

  const uploadFile = async (formData: FormData) => {
    console.log(formData);
    // 自定义上传方法
    // 在这里可以使用你喜欢的方式发送文件上传请求，例如使用axios或者fetch
    // 替换为你自己的上传地址
    // const uploadUrl = "/upload";
    // 发送请求上传文件
    // 例如使用axios：
    try {
      const res = await imageUpload(formData);
      if (res.code === 200) {
        ruleForm.cover = res?.msg;
      }
    } catch (error) {
      console.error(error);
    }
  };

  const handleChange = (item: string) => {
    console.log("change", item);
    ruleForm.content = item;
  };

  const publishDialogVisible = ref(false);

  const publishBtnClick = () => {
    publishDialogVisible.value = true;
  };

  const comfirmClickHandle = async () => {
    ruleFormRef.value &&
      ruleFormRef.value.validate(async valid => {
        if (valid) {
          const params: any = {
            ...ruleForm,
            userId: userInfo.value.userId || ""
          };

          let res;
          try {
            if (type == 0) {
              res = await addArticle(params);
              if (res.code == 200) {
                publishDialogVisible.value = false;
                ruleFormRef.value?.resetFields();
                ElMessage.success("发布成功");
                setTimeout(() => {
                  // router.replace("/community");
                  window.close();
                }, 500);
              }
            } else if (type == 1) {
              res = await updateArticle(params);
              if (res.code == 200) {
                publishDialogVisible.value = false;
                ruleFormRef.value?.resetFields();
                ElMessage.success("修改成功");
                setTimeout(() => {
                  // router.replace("/my");
                  window.close();
                }, 500);
              }
            }
          } catch {
            throw new Error("发布失败");
          }
        } else {
          ElMessage.error("请填写完整信息");
        }
      });
  };

  async function imgUpload(
    formData: FormData,
    success: Function,
    failure: Function
  ) {
    try {
      const res = await imageUpload(formData);
      if (res.code === 200) {
        console.log(res.msg);
        ruleForm.cover = QNURL + res.msg;
      }
    } catch (error) {
      console.error(error);
      failure(console.error);
    }
  }

  async function getArticleDetailFun() {
    const res = await getArticleDetail({ id: articleId });

    if (res.code === 200) {
      ruleForm.title = res.data.title;
      ruleForm.cover = res.data.cover;
      ruleForm.digest = res.data.digest;
      ruleForm.id = res.data.id;
      ruleForm.content = res.data.content;
    }
  }

  onMounted(() => {
    if (articleId) {
      getArticleDetailFun();
    }
  });

  return {
    publishDialogVisible,
    formSize,
    ruleFormRef,
    ruleForm,
    rules,
    type,
    beforeAvatarUpload,
    handleChange,
    publishBtnClick,
    comfirmClickHandle,
    imgUpload
  };
}
